package com.example.jf.jfapp;

import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.example.jf.jfapp.activity.base.BaseActivity;
import com.example.jf.jfapp.adapter.SquareAdapter;
import com.example.jf.jfapp.bean.bean.PariseRequestBean;
import com.example.jf.jfapp.bean.request.UserInfoRequest;
import com.example.jf.jfapp.bean.request.UserStatuRequest;
import com.example.jf.jfapp.bean.response.DongTaiSquareResponse;
import com.example.jf.jfapp.bean.response.UserInfoResponse;
import com.example.jf.jfapp.receiver.CommentReceiver;
import com.example.jf.jfapp.utils.AppConfigUtils;
import com.example.jf.jfapp.utils.Constant;
import com.example.jf.jfapp.utils.OkHttpUtils;
import com.example.jf.jfapp.utils.OperationUtils;
import com.example.jf.jfapp.utils.RequestUtils;
import com.example.jf.jfapp.widget.GlideCircleTransform;
import com.google.gson.Gson;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class OthersActivity extends BaseActivity {
    public static final String OTHERS_KEY = "DATA";
    private TextView tv_name;
    private ImageView iv_pic;
    private TextView tv_focuson_status;
    private DongTaiSquareResponse.ResultBean mResultBean;
    private List<DongTaiSquareResponse.ResultBean> mOtherStatuList = new ArrayList<>();
    private SquareAdapter mOtherAdapter;
    private RecyclerView rl;
    private  String objectId;
    private boolean pariseING = true;//是否可以进行操作

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_others);
        initView();
        getData();
    }
    @Override
    public void initView() {
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setTitle("");

        tv_name = (TextView) findViewById(R.id.tv_name);
        iv_pic = (ImageView) findViewById(R.id.iv_pic);


        tv_focuson_status = (TextView) findViewById(R.id.tv_focuson_status);

        mOtherAdapter = new SquareAdapter(mOtherStatuList,this);

        rl = (RecyclerView) findViewById(R.id.rl);
        rl.setLayoutManager(new LinearLayoutManager(this));
        rl.setAdapter(mOtherAdapter);


        //设置点击事件
        mOtherAdapter.setmClickListener(new SquareAdapter.ActionClickListener() {
            @Override
            public void commentClick(DongTaiSquareResponse.ResultBean resultBean, int position) {

            }

            @Override
            public void pariseClick(DongTaiSquareResponse.ResultBean resultBean, int position) {

            }

            @Override
            public void headClick(DongTaiSquareResponse.ResultBean resultBean, int position) {

            }

            @Override
            public void contentClick(DongTaiSquareResponse.ResultBean resultBean, int position) {

            }
        } );
        registerCommentReceiver();
    }



    /**
     * 点赞
     *
     * @param resultBean
     * @param position
     */
    private void parise(final DongTaiSquareResponse.ResultBean resultBean, final int position) {
        if (pariseING) {
            pariseING = false;
            PariseRequestBean requestBean = new PariseRequestBean();
            requestBean.setStatusId(resultBean.getStatuId());
            requestBean.setUserId(AppConfigUtils.getInstance().getLoginInfo(OthersActivity.this).getObjectId());
            OperationUtils.parise(requestBean, new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            pariseING = true;
                            //取得之前的状态
                            if (resultBean.isPraiseStatus()) {
                                Toast.makeText(OthersActivity.this, "取消失败", Toast.LENGTH_SHORT).show();
                            } else {
                                Toast.makeText(OthersActivity.this, "点赞失败", Toast.LENGTH_SHORT).show();
                            }
                        }
                    });
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            pariseING = true;
                            //取得点赞个数，取消则-1
                            int pariseSize = mOtherStatuList.get(position).getPraiseSize();
                            //判断之前的状态，然后设置点击之后的状态，这里直接本地处理，避免再次请求网络数据
                            if (mOtherStatuList.get(position).isPraiseStatus()) {//如果之前状态为点赞，那么点击后是取消
                                mOtherStatuList.get(position).setPraiseSize(pariseSize - 1);
                                mOtherStatuList.get(position).setPraiseStatus(false);
                                Toast.makeText(OthersActivity.this, "取消成功", Toast.LENGTH_SHORT).show();
                            } else {
                                mOtherStatuList.get(position).setPraiseSize(pariseSize + 1);
                                mOtherStatuList.get(position).setPraiseStatus(true);
                                Toast.makeText(OthersActivity.this, "点赞成功", Toast.LENGTH_SHORT).show();
                            }
                            mOtherAdapter.notifyItemChanged(position);
                        }
                    });
                }
            });
        }
    }

    @Override
    public void getData() {

            objectId = getIntent().getStringExtra(OTHERS_KEY);

            //当前用户id  需要获取信息的用户id
            String userId =getIntent().getStringExtra("userId");
            getUserInfo(userId);


    }

    /**
     * 获取用户信息
     *
     * @param userId
     */
    public void getUserInfo(String userId) {

        final UserInfoRequest userInfoRequest = new UserInfoRequest(userId, mResultBean.getAuthor().getUserId());
        OkHttpClient okHttpClient = OkHttpUtils.getOkHttpClient();
        okHttpClient.newCall(RequestUtils
                .requestPOST(userInfoRequest, Constant.URL.GETUSERSTATUS))
                .enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {

                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        String result = response.body().string();
                        Log.e(TAG, "onResponse其他人的动态: " + result);
                        UserInfoResponse userInfoResponse = new Gson().fromJson(result, UserInfoResponse.class);

                        if (response.code() == 200) {
                            if (userInfoResponse.getResult().getCode() == 200) {
                                updateInfo(userInfoResponse);
                            } else {
                                Toast.makeText(OthersActivity.this, "查询用户信息失败", Toast.LENGTH_SHORT).show();
                            }
                        }
                    }
                });

    }

    /**
     * 获取用户信息成功会，调用此方法更新用户信息
     *
     * @param userInfoResponse
     */
    public void updateInfo(final UserInfoResponse userInfoResponse) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {

                if (AppConfigUtils.getInstance().getLoginInfo(OthersActivity.this).getObjectId().equals(userInfoResponse.getResult().getUserInfo().getObjectId())) {
                    tv_focuson_status.setVisibility(View.GONE);
                    tv_name.setText(userInfoResponse.getResult().getUserInfo().getUsername() + "");
                } else {
                    tv_name.setText(userInfoResponse.getResult().getUserInfo().getUsername() + "");

                    Glide.with(OthersActivity.this)
                            .load(userInfoResponse.getResult().getUserInfo().getHeadProtrait())
                            .transform(new GlideCircleTransform(OthersActivity.this))
                            .diskCacheStrategy(DiskCacheStrategy.ALL)
                            .into(iv_pic);

                    if (userInfoResponse.getResult().getUserInfo().isFolloweeStatus()) {
                        tv_focuson_status.setText("取消关注");
                    } else {
                        tv_focuson_status.setText("点击关注");
                    }
                    tv_focuson_status.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {

                            String url = Constant.URL.getAttentionUrl(AppConfigUtils.getInstance()
                                    .getLoginInfo(OthersActivity.this)
                                    .getObjectId(), objectId);

                            OkHttpClient okHttpClient = OkHttpUtils.getOkHttpClient();

                            Request request;

                            if (userInfoResponse.getResult().getUserInfo().isFolloweeStatus()) {
                                request = RequestUtils.requestDELETE(url);
                            } else {
                                request = RequestUtils.requestPOSTNULL(url);
                            }

                            okHttpClient.newCall(request).enqueue(new Callback() {
                                @Override
                                public void onFailure(Call call, IOException e) {
                                    e.printStackTrace();
                                }

                                @Override
                                public void onResponse(Call call, Response response) throws IOException {
                                    String result = response.body().string();
                                    updateFocusOnInfo(result, userInfoResponse);
                                }
                            });
                        }
                    });
                }
            }
        });
    }
    /**
     * 更新关注信息
     */
    public void updateFocusOnInfo(final String result, final UserInfoResponse userInfoResponse) {

        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Log.e(TAG, "onResponse: " + result);
                if (userInfoResponse.getResult().getUserInfo().isFolloweeStatus()) {
                    Toast.makeText(OthersActivity.this, "取消成功", Toast.LENGTH_SHORT).show();
                    userInfoResponse.getResult().getUserInfo().setFolloweeStatus(false);
                } else {
                    Toast.makeText(OthersActivity.this, "关注成功", Toast.LENGTH_SHORT).show();
                    userInfoResponse.getResult().getUserInfo().setFolloweeStatus(true);
                }

                if (userInfoResponse.getResult().getUserInfo().isFolloweeStatus()) {
                    tv_focuson_status.setText("取消关注");
                } else {
                    tv_focuson_status.setText("点击关注");
                }
            }
        });

    }

    /**
     * 获取用户状态数据
     *
     * @param userInfoRequest
     */
    public void getUserStatus(UserStatuRequest userInfoRequest) {
        OkHttpClient userStatusClient = OkHttpUtils.getOkHttpClient();
        userStatusClient.newCall(RequestUtils
                .requestPOST(userInfoRequest, Constant.URL.GETOTHERUSERSTATUS))
                .enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        showToast("获取个人信息失败");
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        String result = response.body().string();
                        DongTaiSquareResponse statuResponse = new Gson().fromJson(result, DongTaiSquareResponse.class);
                        mOtherStatuList.clear();
                        mOtherStatuList.addAll(statuResponse.getResult());
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                mOtherAdapter.notifyDataSetChanged();
                            }
                        });
                    }
                });
    }

    //注册评论状态的广播
    public void registerCommentReceiver() {
        CommentReceiver.registerReceiver(this, new CommentReceiver.CommentChangeCallback() {
            @Override
            public void changCallback(CommentReceiver.CommentBean commentBean) {
                for (DongTaiSquareResponse.ResultBean bean : mOtherStatuList) {
                    if (bean.getStatuId().equals(commentBean.getStatuId())) {
                        //没有删除评论，所以所有的操作都是增加
                        bean.setCommentsSize(bean.getCommentsSize() + 1);
                        //避免没有必要的循环
                        break;
                    }
                }
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mOtherAdapter.notifyDataSetChanged();
                    }
                });
            }
        });


    }
}
